<template>
  <div id="root">
    <el-row>
      <el-col :span="8" class="root-left">
        <div class="grid-content">
          <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px"
                   class="demo-ruleForm">

            <el-form-item label="开始时间" prop="start">
              <el-date-picker
                v-model="ruleForm.start"
                type="datetime"
                placeholder="加班开始时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="end">
              <el-date-picker
                v-model="ruleForm.end"
                type="datetime"
                placeholder="加班结束时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="加班描述" prop="desc">
              <el-input type="textarea" :row="2" v-model="ruleForm.desc" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="审核部门" prop="checker">
              <el-select v-model="ruleForm.checker" placeholder="选择审核部门">
                <el-option :label="item.label" :value="item.value" v-for="item in options"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="加班照片" prop="file">
              <div class="el-upload-dragger">
                <el-upload
                  class="upload-demo"
                  ref="upload"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :file-list="fileobj"
                  :http-request="httpRequest"
                  :auto-upload="false">
                  <div style="height: 50px" class="el-icon-upload"></div>
                  <div class="el-upload__text"> 将图片拖到此处，或<em>点击上传</em></div>
                </el-upload>
              </div>
            </el-form-item>

            <el-form-item>

              <el-button style="margin-left: 10px;" type="success" @click="submitUpload('ruleForm')">提交
              </el-button>
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="14" class="root-right">
        <h3 style="margin-top: 30px;text-align: left;color: #8c939d">待审核的加班申请</h3>
        <div class="show-message">
          <el-table
            height="420"
            :data="tableDatas"
            style="width: 100%;"
            :default-sort="{prop: 'created', order: 'descending'}"
          >
            <el-table-column
              label="开始时间"
              sortable
              width="100">
               <template slot-scope="scope">
               {{ scope.row.start|dataFMT('YYYY-MM-DD HH:mm:ss') }}
             </template>
            </el-table-column>
            <el-table-column
              prop="end"
              label="结束时间"
              sortable
              width="100">
               <template slot-scope="scope">
               {{ scope.row.end|dataFMT('YYYY-MM-DD HH:mm:ss') }}
             </template>
            </el-table-column>

            <el-table-column
              prop="desc"
              label="加班描述"
            >
            </el-table-column>
            <el-table-column
              prop="image"
              width="100"
              label="加班图片">
              <template slot-scope="scope">
                <div class="demo-image__preview">
                  <el-image
                    style="width: 50px;"
                    :src="scope.row.image"
                    :preview-src-list="[scope.row.image,]">
                  </el-image>
                </div>
              </template>
            </el-table-column>

            <el-table-column
              prop="checker"
              label="审核人"
            >
            </el-table-column>
            <el-table-column label="操作"
                             width="110"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagenation">
          <el-pagination
            small
            layout="prev, pager, next"
            :total="total"
            :page-size="page_size"
            @prev-click="prevfun"
            @next-click="nextfun"
            @current-change="currentchange"
          >
          </el-pagination>
        </div>
      </el-col>
    </el-row>

  </div>
</template>

<script>
  export default {
    name: 'ApplyOvertimeView',
    data () {
      var start = (rule, value, callback) => {
        if (!value || value === '') {
          return callback(new Error('开始时间不能为空'))
        }
        callback()
      }
      var end = (rule, value, callback) => {
        if (!value || value === '') {
          return callback(new Error('结束时间不能为空'))
        }
        if (this.ruleForm.start > this.ruleForm.end) {
          return callback(new Error('结束日期应该晚于开始'))
        }

        callback()
      }
      var desc = (rule, value, callback) => {
        if (!value || value === '') {
          return callback(new Error('出差内容不能为空'))
        }
        callback()
      }
      var checker = (rule, value, callback) => {
        if (!value || value === '') {
          return callback(new Error('审核部门不能为空'))
        }
        callback()
      }
      return {
        hours: '',
        download_url: '',
        fileobj: [],//显示上传的文件
        options: [],//部门
        form: {
          title: '',
          content: ''
        },
        formLabelWidth: '100px',
        visited: false, //控制对话框的弹出
        autosize: { minRows: 6 },
        total: 5, //先设置给初始值，只给空字符串''会报typeerror
        //下一页
        next: '',
        //上一页
        prev: '',
        //每页总数
        page_size: 1,//先设置给初始值，只给空字符串''会报typeerror
        //展示的数据
        tableDatas: [],
        ruleForm: {
          end: '',
          start: '',
          desc: '',
          checker: '',
          image: ''
        },
        rules: {
          checker: [
            {
              required: true,
              message: '审核部门不能为空',
              trigger: 'change'
            }
          ],
          start: [
            {
              validator: start,
              trigger: 'blur'
            }
          ],
          end: [
            {
              validator: end,
              trigger: 'blur'
            }
          ],
          desc: [
            {
              validator: desc,
              trigger: 'blur'
            }
          ],

        }
      }
    },
    mounted () {
      this.download_url = this.$settings.base_url + '/user/downloadfile/'
      //获取部门信息
      this.get_part()
      //获取公司文件
      this.get_data()

    },
    methods: {
      beforeAvatarUpload (file) {
        const isJPG = file.type === 'file/docx'
        const isLt2M = file.size / 1024 / 1024 < 100

        var FileExt = file.name.split('.')[1]
        if (['pdf', 'doc', 'docx'].indexOf(FileExt) === -1) {
          this.$message({
            type: 'warning',
            message: '请上传后缀名为、pdf、doc、docx.'
          })
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 100MB!')
        }
        return isJPG && isLt2M
      },
      downloadfile (index, row) {
        var arr = row.filename.split('.')
        var file_type = arr[arr.length - 1]//获取文件的格式
        this.$axios({
          method: 'get', // 如果是get方法，则写“GET”
          url: this.download_url + `?id=${row.id}`,
          responseType: 'blob'
        })
          .then(res => {

            let blob = new Blob([res.data], {
              type: 'application/msword' //这里需要根据不同的文件格式写不同的参数
            })

            let eLink = document.createElement('a')
            eLink.download = `${row.name}.${file_type}` //给文件名和指定格式
            eLink.style.display = 'none'
            eLink.href = URL.createObjectURL(blob)
            document.body.appendChild(eLink)
            eLink.click()
            URL.revokeObjectURL(eLink.href)
            document.body.removeChild(eLink)
          })
          .catch(err => {
          })

      },

      get_part () {
        this.$axios({
          url: this.$settings.base_url + '/user/partforposition/',
          method: 'get'
        }).then(res => {
          if (res.data.code === 100) {
            this.options = res.data.data
          }
        })
      },
      //submit（）执行后自动调用这个函数
      httpRequest (params) {
        var FileExt = params.file.name.split('.')[1]

        //只能上传pdf格式的文件
        var file_type = ['jpg', 'png', 'JPG', 'PNG'].indexOf(FileExt) === -1
        if (file_type) {
          this.$message({
            type: 'warning',
            message: '请上传jpg或png格式的图片'
          })
          this.fileobj = []
          return
        }
        const isLt2M = params.file.size / 1024 / 1024 < 10
        if (!isLt2M) {
          this.$message.warning('上传的文件大小不能超过10MB')
          return
        }
        this.ruleForm.image = params.file
        var hours = (this.ruleForm.end - this.ruleForm.start) / 1000 / 3600//加班时长
        hours = parseInt(hours)
        var formdata = new FormData()
        formdata.append('image', this.ruleForm.image)
        formdata.append('start', this.$moment(this.ruleForm.start).format('YYYY-MM-DD HH:mm:ss'))
        formdata.append('end', this.$moment(this.ruleForm.end).format('YYYY-MM-DD HH:mm:ss'))
        formdata.append('desc', this.ruleForm.desc)
        formdata.append('checker', this.ruleForm.checker)
        formdata.append('hours', hours)
        console.log(this.ruleForm)
        this.$axios({
          url: this.$settings.base_url + '/user/extrawork/',
          method: 'post',
          data: formdata
        }).then(res => {
          if (res.data.code === 100) {
            this.$message.success('创建成功')
            this.get_data()
            this.resetForm('ruleForm')
            this.fileobj = []
          } else {
            this.$message.error(res.data.error)
          }
        })
      },
      //点击提交时调用这个
      submitUpload (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //前端上传文件到浏览器
            this.$refs.upload.submit()
          } else {
            console.log('error submit!!')
            return false
          }
        })

      },

      resetForm (formName) {
        this.$refs[formName].resetFields()
        this.fileobj = []
      },
      get_data (page = 1) {
        this.$axios({
          url: this.$settings.base_url + `/user/extrawork/?page=${page}&type=${1}`,
          method: 'get'
        }).then(res => {
          //获取到用户信息，赋值给变量
          console.log(res)
          this.tableDatas = res.data.results
          // this.prev = res.data.links.previous
          // this.next = res.data.links.next
          this.total = res.data.count
          this.page_size = res.data.page_size
        })
      },
      prevfun (value) {
        //value拿到的当前的页码,不用传递，内置的函数，自动传递要前往的页码
        this.get_data(value)
      },
      nextfun (value) {
        //value拿到页码
        this.get_data(value)
      },
      currentchange (value) {
        this.get_data(value)

      },

      handleDelete (index, row) {
        console.log(row)
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios({
            url: this.$settings.base_url + `/user/extrawork/?id=${row.id}`,
            method: 'delete',
          }).then(res => {
            if (res.data.code === 100) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.get_data()
            } else {
              this.$message.error('无此数据，无法删除')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    }
  }
</script>

<style scoped>
  .root-left {
    margin-top: 50px;
    margin-right: 50px;
  }

  .el-upload-dragger {
    width: 290px;
    text-align: center;
  }
</style>
